<?php

namespace Home\Controller;
use Home\Org\Util\TTXApi;
use Home\Org\Util\RedisClient;
use Home\Org\Util\Sqlserver;
/**
 * 通天晓WMS相关数据接口 2016-07-22
 * @author dem
 *
 */
class ApiController  extends HomeController{

    public $from='TTX';
    public $company = 'HYW';
    public $warehouse = 'HYWCK';

    function _initialize() {
        header('Content-Type:text/html;Charset=utf-8');
        //header('Content-Type: text/xml');
        import("@.ORG.Util.TTXApi");
        set_time_limit(0);
    }


    /**
     * sap入库失败数据监测
     */
    function exportReceipt(){
        import("@.ORG.Util.Sqlserver");
        $sqlser = new Sqlserver();
        $model = M('ReceiptconfimM');
        $smodel = M('ReceiptconfimS');
        $start = time()-600;
        $data  = $model->where("status is null and ctime <$start")->select();
        $ids = '';
        if(!$data) exit('暂无数据');
        $content = '';
        foreach ($data as $item){
            $ids.=$item['U_wms_id'].',';
            $docentry = $smodel->where("ParentKey={$item['U_wms_id']}")->find()['BaseEntry'];

            $sql = "select DocNum from OPOR where docentry = '{$docentry}'";
            $sapnum = $sqlser->query($sql)[0]['DocNum'];
            $content.= '<br/>sap采购单号:'.$sapnum.'<br/>物料详情:<br/>';
            $sql = "SELECT ItemCode,ItemDescription,Quantity from think_receiptconfim_s where ParentKey={$item['U_wms_id']}";
            $items = $smodel->query($sql);
            foreach ($items as $vo){
                $content.= $vo['ItemCode'].'   '.$vo['ItemDescription'].'   '.$vo['Quantity'].'<br/>';
            }

        }
        $ids=rtrim($ids,',');
        $content.= '<br/><br/>sap数据处理后需执行以下sql修改数据状态:<br/>';
        $content.= "UPDATE think_receiptconfim_s set `status`=1 where ParentKey in ({$ids});<br/>";
        $content.= "UPDATE think_receiptconfim_sq set `status`=1 where ParentKey in ({$ids});<br/>";
        $content.= "UPDATE think_receiptconfim_m set `status`=1 where U_wms_id in ({$ids});<br/>";


        $res =  sendEamilByOA('iterror@g-town.com.cn', '入库失败通知!', $content, null,null);
        print_r($res);
        echo $content;
    }

    function post($uri,$data){
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $uri );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
        $return = curl_exec ( $ch );
        curl_close ( $ch );
        return $return;
    }

    function ordercheck(){
        $str = '';
        $model = M('ReceiptconfimSq');
        $arr = explode("\n", $str);
        echo implode("','", $arr);exit;
        $sss = array();
        foreach ($arr as $ss){
            $ss=rtrim($ss);
            $sql = "select * from think_wms_log where post like '%{$ss}%'";
            $res =  $model->query($sql);
            if($res){

            }else{
                $sss[]=$ss;
            }
        }
        foreach ($sss as $it){
            echo $it."<br/>";
        }
    }

    /**
     * 定时检查wms是否有物料基础信息缺少
     */
    function taskCheckItem(){
        $config = array('host'=>'192.168.1.117','db'=>'SCV','user'=>'TTX','password'=>'ttx2011');
        import("@.ORG.Util.Sqlserver");
        $sqlser = new Sqlserver($config);
        //入库单中物料缺少的
        $sql = "SELECT TOP 3000 USH.COMPANY, SH.RECEIPT_ID, USH.RECEIPT_TYPE, USH.CREATE_DATE_TIME_STAMP as BEGIN_DATE , USH.CREATE_DATE_TIME_STAMP as END_DATE , USH.INTERFACE_CONDITION, SH.ITEM,SH.ITEM_DESC, SH.TOTAL_QTY, SH.QUANTITY_UM, SH.INVENTORY_STS fROM TTX_EAI_DATA.DBO.DOWNLOAD_RECEIPT_HEADER USH(NOLOCK) INNER JOIN TTX_EAI_DATA.DBO.DOWNLOAD_RECEIPT_DETAIL SH (NOLOCK) ON USH.COMPANY=SH.COMPANY collate Chinese_PRC_CI_AI AND USH.RECEIPT_ID=SH.RECEIPT_ID collate Chinese_PRC_CI_AI LEFT JOIN SCV.DBO.ITEM I ON I.ITEM=SH.ITEM collate Chinese_PRC_CI_AI AND I.COMPANY=SH.COMPANY collate Chinese_PRC_CI_AI WHERE I.ITEM IS NULL";
        $data =  $sqlser ->query($sql);
        foreach ($data as $item){
            if($item['ITEM']){
                $this->doitemrequest($item['ITEM'], 'A');
                $updateSql = "update [TTX_EAI_DATA].[dbo].[DOWNLOAD_RECEIPT_HEADER]  SET INTERFACE_CONDITION='READY' WHERE   INTERFACE_CONDITION='FAILED' AND RECEIPT_ID='{$item['RECEIPT_ID']}'";
                $sqlser->saveBysql($updateSql);
            }
        }
        //出库单中物料缺少的
        $sql = "SELECT TOP 3000 USH.COMPANY, SH.SHIPMENT_ID, USH.SHIPMENT_TYPE, USH.CREATE_DATE_TIME_STAMP as BEGIN_DATE , USH.CREATE_DATE_TIME_STAMP as END_DATE , USH.INTERFACE_CONDITION, SH.ITEM,SH.ITEM_DESC, SH.TOTAL_QTY, SH.QUANTITY_UM, SH.INVENTORY_STS fROM TTX_EAI_DATA.DBO.DOWNLOAD_SHIPMENT_HEADER USH(NOLOCK) INNER JOIN TTX_EAI_DATA.DBO.DOWNLOAD_SHIPMENT_DETAIL SH (NOLOCK) ON USH.COMPANY=SH.COMPANY collate Chinese_PRC_CI_AI AND USH.SHIPMENT_ID=SH.SHIPMENT_ID collate Chinese_PRC_CI_AI LEFT JOIN SCV.DBO.ITEM I ON I.ITEM=SH.ITEM collate Chinese_PRC_CI_AI AND I.COMPANY=SH.COMPANY collate Chinese_PRC_CI_AI WHERE I.ITEM IS NULL";
        $data =  $sqlser ->query($sql);
        foreach ($data as $item){
            if($item['ITEM']){
                $this->doitemrequest($item['ITEM'], 'A');
                $updateSql = "update [TTX_EAI_DATA].[dbo].[DOWNLOAD_SHIPMENT_HEADER] SET INTERFACE_CONDITION='READY' WHERE   INTERFACE_CONDITION='FAILED' and SHIPMENT_ID='{$item['SHIPMENT_ID']}'";
                $sqlser->saveBysql($updateSql);
            }
        }
    }

    /**
     * 导出出库回执数据
     */
    function exportOrder(){
        $config = array('host'=>'192.168.1.117','db'=>'SCV','user'=>'TTX','password'=>'ttx2011');
        import("@.ORG.Util.Sqlserver");
        $sqlser = new Sqlserver($config);
        $start = I('start');
        $end = I('end');
        /* $startTime = strtotime($date);
         $model  = M('ShipmentXiaoshouS');
         $data = $model->query("SELECT a.ItemCode, a.FreeText, a.ShipToDescription, b.InternalSerialNumber,ShipToCode FROM think_shipment_xiaoshou_s AS a LEFT JOIN think_shipment_sq AS b ON a.ParentKey = b.ParentKey AND a.LineNum = b.LineNum WHERE a.ctime>{$startTime}"); */
        $sql = "SELECT * from ( SELECT DISTINCT b.ITEM ItemCode, a.ERP_ORDER 'FreeText', CARRIER + '#' + d.TRACKING_NUMBER ShipToDescription, c.SERIAL_NUMBER InternalSerialNumber, ERP_ORDER_LINE_NUM ShipToCode FROM SHIPMENT_HEADER a LEFT JOIN SHIPMENT_DETAIL b ON a.SHIPMENT_ID = b.SHIPMENT_ID LEFT JOIN SERIAL_NUMBER c on c.SHIPMENT_ID=a.SHIPMENT_ID LEFT JOIN SHIPPING_CONTAINER d on d.SHIPMENT_ID=a.SHIPMENT_ID WHERE TRAILING_STS = '900' AND LEADING_STS = '900' and ERP_ORDER_LINE_NUM NOT IN('0','1') and a.CREATE_DATE_TIME>'{$start}' and a.CREATE_DATE_TIME<'{$end}' ) t where t.ShipToDescription is not null";
        $data =  $sqlser ->query($sql);
        Vendor('Excel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue("A".'1', '单号')
            ->setCellValue("B".'1', '手机号码')
            ->setCellValue("C".'1', '快递号')
            ->setCellValue("D".'1',  '快递类型')
            ->setCellValue("E".'1',  '重量')
            ->setCellValue("F".'1',  '序列号');
        $i=2;
        foreach ($data as $row){
            $tempid = str_replace('-', '~', $row['ShipToCode']);
            $expmsg = explode('#', $row['ShipToDescription']);
            IF(!$expmsg) continue;
            if(strpos($row['FreeText'], '~')){
                $order = explode('~', $row['FreeText']);
            }else  if(strpos($row['FreeText'], '#')){
                $order = explode('#', $row['FreeText']);
            }  else{
                $order = explode('@', $row['FreeText']);
            }
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue("A".$i, $order[0].'~'.$tempid)
                ->setCellValue("B".$i, '')
                ->setCellValue("C".$i, $expmsg[1].' ')
                ->setCellValue("D".$i,  $expmsg[0])
                ->setCellValue("E".$i, '1')
                ->setCellValue("F".$i,  $row['InternalSerialNumber']);
            $i++;

        }
        $objPHPExcel->getSheet(0)->getColumnDimension('A')->setWidth(50);
        $objPHPExcel->getSheet(0)->getColumnDimension('C')->setWidth(35);
        $objPHPExcel->getSheet(0)->getColumnDimension('F')->setWidth(35);
        $filename='Order'. date('YmdHis',time());
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');
    }

    /**
     * 导出拣配单
     */
    function exportjpd(){
        import("@.ORG.Util.Sqlserver");
        $start = I('start');
        $end = I('end');
        $sql = "select * from [@ti_z0130] where u_docdate>'{$start}' and  u_docdate<'{$end}' and docentry in (select docentry from [@ti_z0131] where U_WhsCode='HYWCK' )";
        $sqlser = new Sqlserver();
        $data = $sqlser->query($sql);
        foreach ($data as $item){
            echo $item['DocEntry'].' ';
        }
    }


    /**
     * 请求api入口
     * @see \Home\Controller\HomeController::index()
     */
    function index(){
        $fun =strtolower(isset($_SERVER['HTTP_SUBJECT'])?$_SERVER['HTTP_SUBJECT']:'');
        //error_log(var_export($_SERVER,1));//记录所有post
        if($fun){
            $this->$fun();
        }
    }

    /**
     * 出库单队列
     */
    function doqueueByshipmentrequest(){
        ini_set('default_socket_timeout', -1); //redis 基于socket监听  设置永不超时
        import("@.ORG.Util.RedisClient");
        $redis =    RedisClient::instance()->connect();
        $check=true;
        while ($check){
            $res = $redis->blpop('shipmentrequest',10); //阻塞模式,10秒内无数据返回保持监听状态
            if($res){
                $this->doshipmentrequest($res[1]);
            }else{
                $check = false;
            }
        }
        exit;
    }

    function doshipmentrequest($xml){
        //error_log($xml);
        $res   = TTXApi::http('ShipmentRequest', $this->company, $xml,'',false,false);
        return TTXApi::log('queueByshipmentrequest', $xml, $res);
    }



    /**
     *
     * 商品资料同步  第一次同步到wms系统
     * 产品同步接口  //一次同步一个产品
     */
    function itemrequest(){
        $page = (int)I('page');
        $data =  TTXApi::instance()->itemrequest($page); //获取一个产品信息
        if(!$data) exit;
        $header = array('Company'=>'HYW','WareHouse'=>'HYWCK','Type'=>'Add');
        $xml  = TTXApi::createXML('ItemRequest',$header,$data,false);
        $sign = TTXApi::getTTXSign('ItemRequest', $xml,$this->company);
        $res  =  TTXApi::http('ItemRequest','HYW', $xml,$sign,false,false);
        TTXApi::log(__FUNCTION__,$xml, $res);
    }

    /**
     * 日常同步 获取当天新增，修改的物料
     */
    function itemrequestByDate(){
        $itemCode = I('itemCode');
        $type = I('type');
        if(!$itemCode){
            exit;
        }
        $this->doitemrequest($itemCode, $type);
    }

    /**
     * 物料基础信息同步到wms
     * @param unknown $itemCode
     * @param unknown $type
     */
    function doitemrequest($itemCode,$type){
        $data =  TTXApi::instance()->itemrequestByday($itemCode); //获取一个产品信息
        if(!$data) return false;
        $header = array('Company'=>'HYW','WareHouse'=>'HYWCK','Type'=>'');
        foreach ($data as $row){
            $header['Type']=$type=='A'?'Add':'Update';
            unset($row['CreateDate']);
            $xml  = TTXApi::createXML('ItemRequest',$header,array($row),false);
            $sign = TTXApi::getTTXSign('ItemRequest', $xml,$this->company);
            $res  =  TTXApi::http('ItemRequest','HYW', $xml,$sign,false,false);
            TTXApi::log(__FUNCTION__,$xml, $res);
        }
    }

    /**
     * 定时执行 采购入库单 同步到wms
     */
    function receiptrequestBytask(){
        $sql = "select top 10 docentry from opor where u_wms='N'";
        import("@.ORG.Util.Sqlserver");
        $sqlser = new Sqlserver();
        $data = $sqlser->query($sql);
        foreach ($data as $item){
            TTXApi::log('sapsendreceiptrequestId', $item['docentry'], '');
            self::doreceiptrequest('PO', 'getreceiptrequestPOBysap', 'receiptrequestItemsPO',$item['docentry']);
            $sqlser->saveBysql("update opor set u_wms='Y' where docentry='{$item['docentry']}'");

        }
        exit;
    }



    /**
     * 采购入库单 同步到wms  由sap触发 id由sap传参  201703去除触发方式 改为定时任务执行
     */
    function receiptrequestBysap(){
        $id = (int)I('id');
        if(!$id){
            echo 'id not null';exit;
        }
        TTXApi::log('sapsendreceiptrequestId', $id, '');
        self::doreceiptrequest('PO', 'getreceiptrequestPOBysap', 'receiptrequestItemsPO',$id);
        echo $id;
    }

    /**
     * 退货入库(良品库)
     */
    function receiptrequestORBysap(){
        $id = (int)I('id');
        if(!$id){
            echo 'id not null';exit;
        }
        TTXApi::log('sapsendreceiptrequestORId', $id, '');
        self::doreceiptrequest('OR', 'getreceiptrequestORBysap', 'receiptrequestItemsORNew',$id);
        echo $id;
    }


    /**
     * 2 此任务PO类型采购单暂停使用   入库单统一由sap触发
     * 入库单同步  定时脚本
     */
    function receiptrequest(){
        $type = I('type');
        if(!$type){
            echo 'not difine type';exit;
        }
        $ReceiptType = '';
        switch ($type){
            case 'caigou':
                //$ReceiptType='采购入库';
                $ReceiptType='PO';
                break;
            case 'tuihuo':
                //$ReceiptType='退货入库';
                $ReceiptType='OR';
                break;
            case 'diaobo':
                //$ReceiptType='调拨入库';
                $ReceiptType='GIN1';
                break;
        }
        $mfun    = 'getreceiptrequest'.$ReceiptType;
        $itemfun = 'receiptrequestItems'.$ReceiptType;
        if(!$ReceiptType){ echo 'not fund type';exit;}
        echo self::doreceiptrequest($ReceiptType, $mfun, $itemfun);
    }


    /**
     * 入库单同步
     * @param unknown $ReceiptType 单据类型
     * @param unknown $mfun        查询单据主数据方法
     * @param unknown $itemfun     查询单据详情方法
     */
    function doreceiptrequest($ReceiptType,$mfun,$itemfun,$id=''){
        if(!$ReceiptType||!$mfun||!$itemfun) return false;
        $api = TTXApi::instance();
        if($id)
            $orderArr = $api->$mfun($id);//获取一小时内的入库单据
        else
            $orderArr = $api->$mfun();//获取一小时内的入库单据
        $seriesArr = array('13'=>11,'44'=>45);
        foreach ($orderArr as $order){
            if(isset($order['Series'])&&$order['Series'])
                $series= $seriesArr[$order['Series']];
            $headArr = array(
                'Company'=>$this->company,
                'WareHouse'=>$this->warehouse,
                'TotalQty'=>ceil($order['totalqty']),
                'TotalLines'=>$order['totallines'],
                'ReceiptId' =>$order['docentry'],
                'ERP_ORDER_ID' =>$order['docnum'],
                'ReceiptType'=>$ReceiptType,
                'OrderDate'=>$order['docduedate'],
                'SHIP_FROM'=>$order['cardcode'],
                'SHIP_FROM_NAME'=>$order['cardname'],
                'Remark'=>$order['comments'],
                'Series'=>@$series
            );
            $items = $api->$itemfun($order['docentry']);
            $xml   = TTXApi::createXML('ReceiptRequest',$headArr,$items);
            if(!$items[0])
                continue;
            $sign  = TTXApi::getTTXSign('ReceiptRequest', $xml,$this->company);
            $res   = TTXApi::http('ReceiptRequest', $this->company, $xml,$sign,false,false);
            TTXApi::log(__FUNCTION__, $xml, $res);
        }

        return true;
    }

    /**
     * 入库实际
     */
    function receipt(){
        $xmlData = self::getPostXml(false,false);
        $data = json_decode(json_encode((array) simplexml_load_string($xmlData)), true);
        $res = TTXApi::receiptconfim($data);
        if($res)
            $return =  self::respons($res,100);
        else
            $return =  self::respons($res,101,'处理失败');
        TTXApi::log(__FUNCTION__,$xmlData, $return);
        echo $return;

    }

    /**
     * //根据拣配单号 获取订单 ID由sap触发
     * @return boolean
     */
    function shipmentrequestBySap(){
        $id    = (int)I('id');
        if(!$id)return false;
        TTXApi::log('sapsendshipmentId', $id, '');
        import("@.ORG.Util.RedisClient");
        $redis =    RedisClient::instance()->connect();
        set_time_limit(1800);
        //获取出库单
        $api = TTXApi::instance();
        $data = $api->getshipmentrequestBySap($id);
        foreach ($data as $row){
            $headArr = array(
                'Company'=>$this->company,
                'WareHouse'=>$this->warehouse,
                'TotalQty'=>ceil($row['totalqty']),
                'TotalLines'=>$row['totallines'],
                'ShipmentId'=>$row['ShipmentId'],
                'TorderCode'=>$row['u_orderid'],
                'ShipmentType'=>'SO',
                'Carrier'=>$row['U_ExpCom'],
                'BigChar'=>$row['BigChar'],
                'EbillNumber'=>'',
                'Name'=>$row['u_cstname'],
                'PostCode'=>$row['u_zipcode'],
                'Phone'=>$row['phone'],
                'Mobile'=>$row['u_phone'],
                'State'=>$row['u_state'],
                'City'=>$row['u_city'],
                'District'=>$row['u_county'],
                'Address'=>preg_replace('/[^-\w\x80-\xff]/','',$row['u_address']),
                'ShipDate'=>$row['U_DocDate'],
                'ShopName'=>'',
                'DeliveryNote'=>'',
                'ShipmentNote'=>preg_replace('/[^-\w\x80-\xff]/','',$row['u_memo']),
                'CheckDate'=>$row['U_DocDate'],
                'Cod'=>$row['cod'],
                'CodValue'=>$row['codvalue'],
                'Userdef1'=>$row['user_def1'],
                'Userdef2'=>$row['user_def2'],
                'Userdef3'=>$row['user_def3'],
                'Userdef4'=>$row['user_def4'],
                'SHIP_FROM'=>$row['U_CardCode'] //出库单增加供应商字段
            );
            $items = $api->getshipmentrequestItem($row['u_orderid'],$id);
            $xml   = TTXApi::createXML('ShipmentRequest',$headArr,$items);
            $queue = $redis->lPush('shipmentrequest', $xml); //加入队列
            if(!$queue){ //如队列添加失败,直接提交wms
                $sign  = TTXApi::getTTXSign('ShipmentRequest', $xml,$this->company);
                $res = TTXApi::http('ShipmentRequest',  $this->company, $xml, $sign, false, false);
                TTXApi::log(__FUNCTION__, $xml, $res);
            }
        }
        echo $id;

    }


    /**
     * 特殊出库单
     * @return boolean
     */
    function teshushipmentrequestBySap(){
        $id    = (int)I('id');
        if(!$id)return false;
        TTXApi::log('teshusapsendshipmentId', $id, '');
        import("@.ORG.Util.RedisClient");
        $redis =    RedisClient::instance()->connect();
        set_time_limit(1800);
        //获取出库单
        $api = TTXApi::instance();
        $data = $api->teshushipmentrequest($id);
        if(!$data){echo 'data is null';exit;}
        foreach ($data as $row){
            $address = explode('-', $row['u_address']);
            $headArr = array(
                'Company'=>$this->company,
                'WareHouse'=>$this->warehouse,
                'TotalQty'=>ceil($row['totalqty']),
                'TotalLines'=>$row['totallines'],
                'ShipmentId'=>$row['ShipmentId'],
                'TorderCode'=>$row['u_orderid'],
                'ShipmentType'=>$row['shipmenttype'],
                'Carrier'=>isset($address[5])?$address[5]:'',
                'BigChar'=>$row['BigChar'],
                'EbillNumber'=>'',
                'Name'=>isset($address[0])?$address[0]:'',
                'PostCode'=>$row['u_zipcode'],
                'Phone'=>isset($address[1])?$address[1]:'',
                'Mobile'=>isset($address[1])?$address[1]:'',
                'State'=>$row['u_state'],
                'City'=>isset($address[3])?$address[3]:'',
                'District'=>isset($address[2])?$address[2]:'',
                'Address'=>isset($address[4])?$address[4]:'',
                'ShipDate'=>$row['U_DocDate'],
                'ShopName'=>'',
                'DeliveryNote'=>'',
                'ShipmentNote'=>$row['u_memo'],
                'CheckDate'=>$row['U_DocDate'],
                'Cod'=>$row['cod'],
                'CodValue'=>$row['codvalue'],
                'Userdef1'=>$row['user_def1'],
                'Userdef2'=>$row['user_def2'],
                'Userdef3'=>$row['user_def3'],
                'Userdef4'=>$row['user_def4'],
                'SHIP_FROM'=>$row['U_CardCode'] //出库单增加供应商字段
            );
            $items = $api->getTeshushipmentrequestItem($id);
            $xml   = TTXApi::createXML('ShipmentRequest',$headArr,$items);
            $queue = $redis->lPush('shipmentrequest', $xml); //加入队列
            if(!$queue){ //如队列添加失败,直接提交wms
                $sign  = TTXApi::getTTXSign('ShipmentRequest', $xml,$this->company);
                $res = TTXApi::http('ShipmentRequest',  $this->company, $xml, $sign, false, false);
                TTXApi::log(__FUNCTION__, $xml, $res);
            }
        }
        echo $id;

    }


    /**
     * 3   此接口定时任务执行,已弃用。
     * 出库单同步
     * 加入redis队列
     */
    function shipmentrequest(){

        import("@.ORG.Util.RedisClient");
        $redis =    RedisClient::instance()->connect();
        set_time_limit(1800);
        //获取出库单
        $api = TTXApi::instance();
        $data = $api->getshipmentrequest(5);//获取5分钟内出库单
        foreach ($data as $row){
            $headArr = array(
                'Company'=>$this->company,
                'WareHouse'=>$this->warehouse,
                'TotalQty'=>ceil($row['totalqty']),
                'TotalLines'=>$row['totallines'],
                'ShipmentId'=>$row['u_orderid'],
                'TorderCode'=>$row['u_orderid'],
                'ShipmentType'=>'SO',
                'Carrier'=>$row['U_ExpCom'],
                'BigChar'=>$row['BigChar'],
                'EbillNumber'=>'',
                'Name'=>$row['u_cstname'],
                'PostCode'=>$row['u_zipcode'],
                'Phone'=>$row['phone'],
                'Mobile'=>$row['u_phone'],
                'State'=>$row['u_state'],
                'City'=>$row['u_city'],
                'District'=>$row['u_county'],
                'Address'=>$row['u_address'],
                'ShipDate'=>$row['U_DocDate'],
                'ShopName'=>'',
                'DeliveryNote'=>'',
                'ShipmentNote'=>$row['u_memo'],
                'CheckDate'=>$row['U_DocDate'],
                'Cod'=>$row['cod'],
                'CodValue'=>$row['codvalue'],
                'Userdef1'=>$row['user_def1'],
                'Userdef2'=>$row['user_def2'],
                'Userdef3'=>$row['user_def3'],
                'Userdef4'=>$row['user_def4'],
                'SHIP_FROM'=>$row['U_CardCode'] //出库单增加供应商字段
            );
            $items = $api->getshipmentrequestItem($row['u_orderid'],$row['DocEntry']);
            $xml   = TTXApi::createXML('ShipmentRequest',$headArr,$items);
            $queue = $redis->lPush('shipmentrequest', $xml); //加入队列
            if(!$queue){ //如队列添加失败,直接提交wms
                $sign  = TTXApi::getTTXSign('ShipmentRequest', $xml,$this->company);
                $res = TTXApi::http('ShipmentRequest',  $this->company, $xml, $sign, false, false);
                TTXApi::log(__FUNCTION__, $xml, $res);
            }
        }

    }

    /**
     * 出库实际
     */
    function shipment(){
        $xml='<?xml version="1.0" encoding="utf-8"?>

<SHIPMENT>
  <SHIPMENT>
    <Company>HYW</Company>
    <WareHouse>HYWCK</WareHouse>
    <ShipmentId>P16110714380521~17345</ShipmentId>
    <ShipmentType>SO</ShipmentType>
    <Carrier>ZTO</Carrier>
    <TrackingNumber>532763501201</TrackingNumber>
    <SuppliesId>18421-29</SuppliesId>
    <SHIP_FROM>C20036</SHIP_FROM>
    <SHIP_FROM_NAME/>
    <Weight>710.00000</Weight>
    <OQCBench/>
    <Remark/>
    <ShipmentDate>2016-11-07 14:12:00</ShipmentDate>
    <Items>
      <Item>
        <Item>B10012645</Item>
        <ItemName>爱国者WQ-1601键盘鼠标套装有线 防水游戏家用台式笔记本键鼠：黑色</ItemName>
        <ItemCount>1</ItemCount>
        <InventorySts/>
        <ExpirationDate>N</ExpirationDate>
        <ManSernum/>
        <Erporderlinenum>18421-29</Erporderlinenum>
        <Polineid/>
        <Sprice>42.00000</Sprice>
      </Item>
    </Items>
  </SHIPMENT>
</SHIPMENT>
    
    
    ';
        $xmlData = self::getPostXml(false,false);
        $data = json_decode(json_encode((array) simplexml_load_string($xmlData)), true);

        if(in_array($data['SHIPMENT']['SHIP_FROM'],array('C20050','C20020','C20007','C20086','C20101','C20088'))){
            $this->sendSMSByShipped(array('u_orderid'=>$data['SHIPMENT']['ShipmentId'],'u_expno'=>$data['SHIPMENT']['TrackingNumber'],'u_expcom'=>$data['SHIPMENT']['Carrier'],'u_cardcode'=>$data['SHIPMENT']['SHIP_FROM']));
        }

        if(!$data['SHIPMENT'][0]){
            $data['SHIPMENT']=array('SHIPMENT'=>$data['SHIPMENT']);
        }
        $api = TTXApi::instance();
        foreach ($data['SHIPMENT'] as $vo){
            $res=$api->shipmentConfim(array('SHIPMENT'=>$vo));
        }

        if($res)
            $return =  self::respons($res,100);
        else
            $return =  self::respons($res,101,'处理失败');

        TTXApi::log(__FUNCTION__,$xmlData, $return);
        echo $return;

    }

    /**
     * 4
     * 出库单取消
     */
    function shipmentcancelrequest(){
        $id = I('id');
        if(!$id){echo 'ShipmentId not null';exit;}
        $header = array('Company'=>$this->company,'WareHouse'=>$this->warehouse,'ShipmentId'=>$id,'Remark'=>'出库取消');
        $xml    = TTXApi::createXML('ShipmentCancelRequest',$header,array());
        $sign   = TTXApi::getTTXSign('ShipmentCancelRequest', $xml,$this->company);
        $res    = TTXApi::http('ShipmentCancelRequest',  $this->company, $xml, $sign, false, false);
        TTXApi::log(__FUNCTION__, $xml, $res);
        echo $id;
    }


    /**
     * 出库状态通知
     */
    function deliverystatusnotification(){

    }

    /**
     * 条码修改回传
     */
    function alterbarcode(){

        $xmlData = self::getPostXml(false,false);
        $data = json_decode(json_encode((array) simplexml_load_string($xmlData)), true);
        if(!isset($data['barcode'])||!$data['barcode']){
            $return =  self::respons(0,101,'barcode  undifined');
            TTXApi::log(__FUNCTION__,$xmlData, $return);
            echo $return;
            exit;
        }

        if(!isset($data['item'])||!$data['item']){
            $return =  self::respons(0,101,'item  undifined');
            TTXApi::log(__FUNCTION__,$xmlData, $return);
            echo $return;
            exit;
        }

        $res = TTXApi::instance()->updateItemCodebars($data['barcode'], $data['item']);
        $return =  self::respons(1,100);
        TTXApi::log(__FUNCTION__,$xmlData, $return);
        echo $return;

    }

    /***
     * 复核打印发票
     */
    function packingprint(){
        $xmlData = self::getPostXml(false,false);
        $return =  self::respons(1,100);
        TTXApi::log(__FUNCTION__,$xmlData, $return);
        echo $return;
    }



    /**
     * 数组转xml
     * @param unknown $data
     * @param string $rootNodeName
     * @param string $xml
     */
    public static function toXml($data, $rootNodeName = 'data', $xml=null)
    {
        if (ini_get('zend.ze1_compatibility_mode') == 1)
        {
            ini_set ('zend.ze1_compatibility_mode', 0);
        }

        if ($xml == null)
        {
            $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$rootNodeName />");
        }

        foreach($data as $key => $value)
        {
            if (is_numeric($key))
            {
                $key = "unknownNode_". (string) $key;
            }

            $key = preg_replace('/[^a-z]/i', '', $key);

            if (is_array($value))
            {
                $node = $xml->addChild($key);
                self::toXml($value, $rootNodeName, $node);
            }
            else
            {
                $value = htmlentities($value);
                $xml->addChild($key,$value);
            }

        }
        return $xml->asXML();
    }

    /**
     * 返回处理结果
     * @param number $isSuccess  是否成功 1 成功 0 失败
     * @param number $code       Code
     * @param string $des        说明
     */
    function respons($isSuccess=1,$code=100,$des='单据接受成功'){
        $respons =array('Success'=>$isSuccess?'true':'false','Code'=>$code,'Description'=>$des);
        return self::toXml($respons,'Response');
        //结束
    }

    /**
     * 获取请求xml 返回数组
     * @param string $testXML
     * @return mixed
     */
    function getPostXml($testXML='',$is_returnXML=true){
        //$xml =  $HTTP_RAW_POST_DATA;//获取xml
        $xml =  file_get_contents('php://input');
        if($testXML) $xml=$testXML;
        if($is_returnXML){
            $data = json_decode(json_encode((array) simplexml_load_string($xml)), true);
            return $data;
        }else{
            return $xml;
        }
    }

    public function updateBillStatus(){
        $id = I('id');
        if(!$id) echo false;
        $funArr = array('ReceiptconfimM','DiaoboM','TuihuoM','ShipmentCaigouM','ShipmentDiaoboM','ShipmentXiaoshouM');
        $fun = I('fun');
        if(!in_array($fun,$funArr))exit;
        $status = I('status');
        echo TTXApi::UpdateBillStatus($fun,$id,$status);
    }

    function colsereceipt(){
        $docentry = I('docentry');
        if($docentry){
            $res =  $this->ReceiptCancelRequest($docentry);
        }
    }



    function testqueue(){
        ini_set('default_socket_timeout', -1); //redis 基于socket监听  设置永不超时
        import("@.ORG.Util.RedisClient");
        $redis =    RedisClient::instance()->connect();
        while (true){
            $res = $redis->blpop('test',100); //阻塞模式,100秒内无数据返回保持监听状态
            if($res){
                echo $res[1]."\n";
            }
        }
    }


    function taskKillDTW(){
        exec('TASKLIST /FI "USERNAME ne NT AUTHORITY\SYSTEM" /FI "STATUS eq NOT RESPONDING"',$output); //查询非系统 未响应的进程
        if(iconv('gbk', 'utf-8', $output[0])=='信息: 没有运行的任务匹配指定标准。'){
            echo 'not fund NOT RESPONDING PID';
            exit();
        }
        foreach ($output as $task){
            $ts = explode(' ', $task);
            if($ts[0]=='DTW.exe'){
                foreach ($ts as $tsmsg){
                    $pid = doubleval($tsmsg);
                    if(($pid)){
                        exec("tskill {$pid}",$killpidout);
                        print_r($killpidout);
                    }

                }
            }
        }
    }

    /**
     * 顺丰快递查询官方接口
     */
    function SFApi(){
        $wsdluri = 'http://bsp-oisp.sf-express.com/bsp-oisp/ws/sfexpressService?wsdl';
        $uri = 'http://218.17.248.244:11080/bsp-oisp/sfexpressService';
        $code = '0213628980 ';
        $checkWord = 'JF7J5Iun5U68O996zJHWGhFbRAQUPzyX'; //密钥
        $xml =  new \DOMDocument('1.0','UTF-8');
        $doc =  $xml->formatOutput = true;
        $root = $xml->createElement('Request');
        $root->setAttribute('service', 'RouteService');
        $root->setAttribute('lang', 'zh-CN');
        $head = $xml->createElement('Head',$code);
        $body = $xml->createElement('Body');
        $RouteRequest = $xml->createElement('RouteRequest');
        $RouteRequest->setAttribute('tracking_type', 1);
        $RouteRequest->setAttribute('method_type', 1);
        $RouteRequest->setAttribute('tracking_number', 926358887403);
        $body->appendChild($RouteRequest);

        $root->appendChild($head);
        $root->appendChild($body);
        $xml->appendChild($root);
        $xml = $xml->saveXML();
        $signStr = $xml.$checkWord;
        $md5signStr = md5($signStr,true);
        $sign = base64_encode($md5signStr);

        $client = new \SoapClient($wsdluri);

        $param = array('arg0'=>$xml,'arg1'=>$sign);
        $ret = $client->sfexpressService($param);
        $array=(array)$ret;
        print_r($array);

        exit;



        $data = array('xml'=>$xml,'verifyCode'=>$sign);
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $uri );
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        $return = curl_exec ( $ch );
        curl_close ( $ch );

        print_r($return);

    }

    /**
     * 采购单取消  由sap触发
     */
    function ReceiptCancelRequest($id){

        if(!$id){echo 'ReceiptID not null';exit;}
        $header = array('Company'=>$this->company,'WareHouse'=>$this->warehouse,'ReceiptId'=>$id,'Remark'=>'入库单取消 '.date('Y-m-d H:i:s'));
        $xml    = TTXApi::createXML('ReceiptCancelRequest',$header,array());
        $sign   = TTXApi::getTTXSign('ReceiptCancelRequest', $xml,$this->company);
        $res    = TTXApi::http('ReceiptCancelRequest',  $this->company, $xml, $sign, false, false);
        TTXApi::log(__FUNCTION__, $xml, $res);
        echo $id;
    }

    /**
     * 每日23.59分 定时将出库单导入sap发货临时表
     */
    function taskShipment(){
        set_time_limit(1800);
        $date  = date('Y-m-d');
        // $date = '2016-10-11';
        $start = strtotime($date);
        $model = M('ShipmentXiaoshouS');
        $end   = strtotime($date.' 23:59:59');
        //获取当天总量
        $totalSql = "SELECT  count(1) as total from think_shipment_xiaoshou_s a  LEFT  JOIN think_shipment_sq as b on a.ParentKey=b.ParentKey and a.LineNum=b.LineNum and  b.s_type='SO' where a.ctime>$start and a.ctime<$end  ";
        $total = $model->query($totalSql)[0]['total'];
        $pageSize = 50;
        $totalPage = $total%$pageSize==0?(int)$total/$pageSize:(int)($total/$pageSize)+1; //分页
        $querSql = "SELECT  a.ShipToCode docEntry ,FreeText 'OrderId',ShipToDescription,Width1,b.InternalSerialNumber serNo from think_shipment_xiaoshou_s a  LEFT  JOIN think_shipment_sq as b on a.ParentKey=b.ParentKey and a.LineNum=b.LineNum and  b.s_type='SO' where a.ctime>{$start} and a.ctime<{$end}  ORDER BY docEntry  ";

        import("@.ORG.Util.Sqlserver");
        $sqlser = new Sqlserver();
        //批量插入
        $insertSqlPriex = "INSERT into Import_Z0090 (docentry,Lineid,orderid,Phone,ExpNo,ExpCom,Weight,SerNum) VALUES";
        for($i=1;$i<=$totalPage;$i++){
            $limit = ($i-1)*$pageSize .','.$pageSize;
            $pageSql =  $querSql.' limit '.$limit;
            $list = $model->query($pageSql);
            $values = '';
            foreach ($list as $vo){
                $doc_line  = explode('-', $vo['docEntry']);

                //解决特殊订单格式数据问题
                if(strpos($vo['OrderId'], '~')){
                    $orderTemp = explode('~', $vo['OrderId']);
                }else  if(strpos($vo['OrderId'], '#')){
                    $orderTemp = explode('#', $vo['OrderId']);
                }  else{
                    $orderTemp = explode('@', $vo['OrderId']);
                }

                $exp       = explode('#', $vo['ShipToDescription']);
                $width     = ((int)$vo['Width1'])/1000;
                $values.="('{$doc_line[0]}','{$doc_line[1]}','{$orderTemp[0]}','','{$exp[1]}','{$exp[0]}','{$width}','{$vo['serNo']}'),";
            }
            $saveSql = $insertSqlPriex.rtrim($values,',');
            $sqlser->saveBysql($saveSql);
        }
    }
    // start -------- sap 订单 状态更新 发送短信 上海银行 广发银行
    /**
     * 订单状态更新为减配时 发送短信通知用户
     */
    function sendSMSByJP(){
        $docentry = intval(I('id'));
        $cardName = I('cname')?:'上海银行-信用卡积分';//'广发银行-分期商城'
        if(!$docentry) exit('Invalid Docentry ');
        $date =date("Y-m-d ", strtotime("-30 day"));
        //$sql = "SELECT a.u_orderid,a.u_phone,a.u_expno,a.u_expcom,b.u_cardcode  from [@ti_z0081] a LEFT JOIN [@TI_Z0080] b on a.docentry=b.DocEntry  where  a.Docentry='{$docentry}' and a.u_docDate>'{$date}' and b.u_cardcode in ('C20050','C20020')";
        $sql = "SELECT c.u_orderid, c.u_phone, a.u_expno, a.u_expcom, d.u_cardcode FROM [@TI_Z0131] a LEFT JOIN [@TI_Z0130] b ON a.docentry = b.DocEntry LEFT JOIN [@TI_Z0081] c ON a.U_BsEntry = c.DocEntry AND a.U_BsLine = c.LineId LEFT JOIN [@TI_Z0080] d ON d.DocEntry = c.DocEntry WHERE  a.Docentry='{$docentry}' and c.u_docDate>'{$date}' and d.u_cardcode in ('C20050','C20020','C20101')";
        import("@.ORG.Util.Sqlserver");
        $sqlser = new Sqlserver();
        $orderList = $sqlser->query($sql);
        $msmModel = "尊敬的客户您好!您在cname订购的商品我司已收到.订单号:order,2个工作日安排发货,发货时间以实际收到发货短信为准,如有问题请拨打400-006-6830.";
        $shipped_msmModel    = "尊敬的客户您好!您在cname订购的商品已由expcom发货.订单号：order,快递单号：expno,请您注意查收，谢谢！如有问题请致电400-006-6830.";
        $shipped_msmModel_sh = "尊敬的客户您好!您在cname兑换的礼品已由expcom发货.快递单号:expno,请您注意查收,谢谢!如有问题请致电400-006-6830."; //上海银行短信模板
        $shipped_msmModel_jhlk = "尊敬的客户您好！您在cname订购的商品我司已接单。订单号：order，发货时间以实际收到发货短信为准，如有问题请拨打海牙湾服务热线400-006-6830。"; //海牙湾建行龙卡专区短信模板
        if($orderList){
            foreach ($orderList as $orderinfo){
                if($orderinfo['u_cardcode']=='C20020') { //广发银行发送拣配短信
                    $this->_smspushqueue(array('phone' => $orderinfo['u_phone'], 'content' => str_replace(array('cname', 'order'), array($this->_getCnameBycode($orderinfo['u_cardcode']), $orderinfo['u_orderid']), $msmModel) . $this->_getsmsfix($orderinfo['u_cardcode'])));
                }else if($orderinfo['u_cardcode']=='C20101')
                {
                    $this->_smspushqueue(array('phone'=>$orderinfo['u_phone'],'content'=>str_replace(array('cname','order'), array($this->_getCnameBycode($orderinfo['u_cardcode']),$orderinfo['u_orderid']), $shipped_msmModel_jhlk).$this->_getsmsfix($orderinfo['u_cardcode'])));

                }
                if($orderinfo['u_expno']){
                    //代发订单  同时发送发货短信
                    $smscontent = $orderinfo['u_cardcode']=='C20050'?$shipped_msmModel_sh:$shipped_msmModel;
                    $this->_smspushqueue(array('phone'=>$orderinfo['u_phone'],'content'=> str_replace(array('cname','order','expcom','expno'), array($this->_getCnameBycode($orderinfo['u_cardcode']),$orderinfo['u_orderid'],$orderinfo['u_expcom'],$orderinfo['u_expno']) ,$smscontent).$this->_getsmsfix($orderinfo['u_cardcode'])));
                }

            }
        }
        echo $docentry;
        exit;
    }
    /**
     * 发送已发货短信通知用户
     */
    function sendSMSByShipped($orderinfo){
        import("@.ORG.Util.Sqlserver");
        list($orderId,$docentry) = explode('~', $orderinfo['u_orderid']);
        $sqlser = new Sqlserver();
        $sql ="SELECT u_phone from [@ti_z0081] where u_orderid='{$orderId}' ";
        $orderList = $sqlser->query($sql);
        if(!isset($orderList[0]))
            return false;
        $orderinfo['u_orderid'] = $orderId;
        $orderinfo['u_phone']  = $orderList[0]['u_phone'];
        switch ($orderinfo['u_cardcode']){
            case 'C20050':
                $shipped_msmModel = "尊敬的客户您好!您在cname兑换的礼品已由expcom发货.快递单号:expno,请您注意查收,谢谢!如有问题请致电400-006-6830.";
                break;
            case 'C20020':
                $shipped_msmModel = "尊敬的客户您好!您在cname订购的商品已由expcom发货.订单号:order,快递单号:expno,请您注意查收,谢谢!如有问题请致电400-006-6830.";
                break;
            case 'C20007':
                $shipped_msmModel = "尊敬的客户您好！您在cname兑换的礼品已由expcom发货。快递单号：expno，请您注意查收，谢谢！如有问题请致电400-006-6830.";
                break;
            case 'C20086':

                $shipped_msmModel = "尊敬的客户您好！您在cname获得的神偷奶爸系列信用卡刷卡赠礼，礼品已由expcom发货。快递单号：expno，请您注意查收，谢谢！如有问题请致电400-006-6830.";
                break;
            case 'C20101':
                $shipped_msmModel = "尊敬的客户您好！您在cname订购的商品已发货。 订单号：order，请您注意查收，谢谢！如有问题请致电海牙湾服务热线400-006-6830。";
                break;
            case 'C20088':
                $shipped_msmModel = "您在上海银行领取的跨年礼品，已由expcom快递发货。快递单号：expno，请注意查收，谢谢！如有问题请致电400-006-6830。";
                break;
        }


        return  $this->_smspushqueue(array('phone'=>$orderinfo['u_phone'],'content'=> str_replace(array('cname','order','expcom','expno'), array($this->_getCnameBycode($orderinfo['u_cardcode']),$orderinfo['u_orderid'],$orderinfo['u_expcom'],$orderinfo['u_expno']) ,$shipped_msmModel).$this->_getsmsfix($orderinfo['u_cardcode'])));

    }



    function _getsmsfix($code){
        $cnamelist =array('C20050'=>'(上海银行合作商)','C20020'=>'(广发商城合作商)','C20007'=>'(建设银行合作商)','C20086'=>'(中国银行合作商)','C20101'=>'','C20088'=>'(上海银行合作商)');
        return isset($cnamelist[$code])?$cnamelist[$code]:'';
    }

    /**
     * 根据平台code 获取平台名称
     */
    function _getCnameBycode($code){
        $cnamelist =array('C20050'=>'上海银行','C20020'=>'广发商城','C20007'=>'建行积分商城','C20086'=>'中国银行','C20101'=>'海牙湾商城龙卡专区');
        return isset($cnamelist[$code])?$cnamelist[$code]:'';
    }



    /**
     * 加入短信队列
     * $data array('phone'=>'',content=>'');
     */
    function _smspushqueue($data=array()){
        import("@.ORG.Util.RedisClient");
        $redis =    RedisClient::instance()->connect();
        $queue = $redis->lPush('orderSMSByOA', json_encode($data)); //加入队列
        return $queue;
    }

    function sendOrderSMSByTask(){
        ini_set('default_socket_timeout', -1);
        import("@.ORG.Util.RedisClient");
        $redis =    RedisClient::instance()->connect();
        $check=true;
        while ($check){
            $res = $redis->lPop('orderSMSByOA');
            if($res){
                $data = json_decode($res,true);
                if(isset($data['phone'])||isset($data['content'])||$this->_checkPhone($data['phone'])){
                    $data['phone'] = rtrim($data['phone']);
                    $data['phone'] = ltrim($data['phone']);
                    $data['phone'] = substr( $data['phone'], 0,11);
                    $res =  $this->_sendSMS($data['phone'], $data['content']);
                    // error_log($data['phone'].var_export($res,1));
                }


            }else{
                // $check = false;
            }
        }
        exit('SUCCESS');

    }

    /**
     * 检查手机号码
     * @param unknown $phone
     */
    function _checkPhone($phone){
        return  true;
    }



    /**
     * 调用发送短信接口
     * @param unknown $phone
     * @param unknown $content
     * @return multitype:
     */
    function _sendSMS($phone,$content){
        $api = "http://sms.g-town.com.cn/sms/?service=Message.Send";
        $params = array(
            'phone'  =>$phone,
            'content'=>$content,
            'sysCode' =>'OA'
        );
        return  http($api, $params,'POST');
    }

    // end -------- sap 订单 状态更新 发送短信 上海银行 广发银行

    /**
     * 自检测短信进程
     */
    function checkOrderSMSProcess(){

        $command = 'wmic process  get caption,commandline /value | findstr "sendOrder"';
        exec($command,$output);
        print_r($output);
        if(count($output)<3){
            exec('php C:\wamp\www\g-townOA\cli.php api/sendOrderSMSByTask');
        }
    }
}